package com.rhb.oa.news.dao;

import java.util.*;

import com.rhb.oa.news.bean.*;
import com.rhb.util.UID;

import org.hibernate.Query;
import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class NewsDAO_HibernateImpl extends HibernateDaoSupport implements
		NewsDAO {
	static Logger logger = Logger.getLogger(NewsDAO_HibernateImpl.class);

	public void delete(News obj) {
		try {
			this.getHibernateTemplate().delete(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public News findByPK(String pk) {
		return (News) this.getHibernateTemplate().get(News.class, pk);
	}

	public String create(News obj) {
		String pk = UID.getUID();
		obj.setNewsPk(pk);
		try {
			this.getHibernateTemplate().save(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pk;
	}

	public void update(News obj) {
		try {
			this.getHibernateTemplate().update(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Query getQuery(String str, NewsQuery quester, String orderBy) {
		StringBuffer hql = new StringBuffer(str);
		if (quester != null) {
			if (quester.getTitle() != null && !"".equals(quester.getTitle())) {
				hql.append(" and title like :title");
			}

			if (quester.getType() != null && !"".equals(quester.getType())) {
				hql.append(" and type like :type");
			}
		}
		
		if (orderBy != null) {
				hql.append(orderBy);
		}

		Query query = this.getSession().createQuery(hql.toString());
		if (quester != null) {
			if (quester.getTitle() != null && !"".equals(quester.getTitle())) {
				query.setString("title", "%"
						+ String.valueOf(quester.getTitle()) + "%");
			}

			if (quester.getType() != null && !"".equals(quester.getType())) {
				query.setString("type", "%" + String.valueOf(quester.getType())
						+ "%");
			}

		}
		return query;
	}

	public int getAllCount_findByQuery(NewsQuery quester) {
		Long allcount = new Long(0);
		String hql = "select count(news) from News news where 1=1";
		try {
			Query query = getQuery(hql, quester,null);
			Iterator result = query.iterate();
			if (result.hasNext()) {
				allcount = (Long) result.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return allcount.intValue();
	}

	public List findByQuery(NewsQuery quester, int start, int count) {
		String hql = "select news from News news where 1=1";
		String orderBy = " order by madeDate desc";
		try {
			Query query = getQuery(hql, quester,orderBy);
			query.setFirstResult(start);
			query.setMaxResults(count);

			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
